/*
 * @Author: AuroCaffe 18509564594@163.com
 * @Date: 2025-01-06 18:51:49
 * @LastEditors: AuroCaffe 18509564594@163.com
 * @LastEditTime: 2025-01-06 18:51:49
 * @FilePath: \HuiLin\utils\emergencyCleaner.js
 * @Description: 紧急清理工具 - 强制清理所有资源防止卡死
 */

// 全局定时器ID追踪
let globalTimerIds = new Set();
let globalIntervalIds = new Set();

// 重写setTimeout和setInterval来追踪
const originalSetTimeout = global.setTimeout;
const originalSetInterval = global.setInterval;
const originalClearTimeout = global.clearTimeout;
const originalClearInterval = global.clearInterval;

// 重写setTimeout
global.setTimeout = function(callback, delay, ...args) {
    const timerId = originalSetTimeout(callback, delay, ...args);
    globalTimerIds.add(timerId);
    return timerId;
};

// 重写setInterval
global.setInterval = function(callback, delay, ...args) {
    const intervalId = originalSetInterval(callback, delay, ...args);
    globalIntervalIds.add(intervalId);
    return intervalId;
};

// 重写clearTimeout
global.clearTimeout = function(timerId) {
    globalTimerIds.delete(timerId);
    return originalClearTimeout(timerId);
};

// 重写clearInterval
global.clearInterval = function(intervalId) {
    globalIntervalIds.delete(intervalId);
    return originalClearInterval(intervalId);
};

class EmergencyCleaner {
    constructor() {
        this.cleanupHistory = [];
        this.lastCleanupTime = 0;
        this.cleanupInterval = 10000; // 10秒清理一次
    }

    /**
     * 强制清理所有定时器
     */
    forceCleanupAllTimers() {
        console.log('[EmergencyCleaner] 开始强制清理所有定时器');
        
        // 清理所有setTimeout
        globalTimerIds.forEach(timerId => {
            try {
                originalClearTimeout(timerId);
            } catch (error) {
                console.warn('[EmergencyCleaner] 清理setTimeout失败:', timerId, error);
            }
        });
        
        // 清理所有setInterval
        globalIntervalIds.forEach(intervalId => {
            try {
                originalClearInterval(intervalId);
            } catch (error) {
                console.warn('[EmergencyCleaner] 清理setInterval失败:', intervalId, error);
            }
        });
        
        // 清空追踪集合
        globalTimerIds.clear();
        globalIntervalIds.clear();
        
        console.log('[EmergencyCleaner] 强制清理完成');
        
        // 记录清理历史
        this.cleanupHistory.push({
            timestamp: Date.now(),
            timerCount: globalTimerIds.size,
            intervalCount: globalIntervalIds.size,
            type: 'force'
        });
        
        // 限制历史记录数量
        if (this.cleanupHistory.length > 10) {
            this.cleanupHistory.shift();
        }
    }

    /**
     * 清理页面相关资源
     */
    cleanupPageResources() {
        console.log('[EmergencyCleaner] 清理页面资源');
        
        // 清理可能的WebSocket连接
        try {
            if (typeof uni !== 'undefined' && uni.closeSocket) {
                uni.closeSocket();
            }
        } catch (error) {
            console.warn('[EmergencyCleaner] 清理WebSocket失败:', error);
        }
        
        // 清理可能的网络请求
        try {
            if (typeof uni !== 'undefined' && uni.request) {
                // 这里可以添加请求取消逻辑
            }
        } catch (error) {
            console.warn('[EmergencyCleaner] 清理网络请求失败:', error);
        }
        
        // 强制垃圾回收（如果支持）
        if (typeof global !== 'undefined' && global.gc) {
            try {
                global.gc();
                console.log('[EmergencyCleaner] 强制垃圾回收完成');
            } catch (error) {
                console.warn('[EmergencyCleaner] 垃圾回收失败:', error);
            }
        }
    }

    /**
     * 检查是否需要清理
     */
    checkAndCleanup() {
        const now = Date.now();
        
        // 限制清理频率
        if (now - this.lastCleanupTime < this.cleanupInterval) {
            return;
        }
        
        const totalTimers = globalTimerIds.size + globalIntervalIds.size;
        
        // 如果定时器数量过多，执行清理
        if (totalTimers > 15) {
            console.warn(`[EmergencyCleaner] 检测到过多定时器: ${totalTimers}，执行清理`);
            this.forceCleanupAllTimers();
            this.cleanupPageResources();
            this.lastCleanupTime = now;
        }
    }

    /**
     * 获取统计信息
     */
    getStats() {
        return {
            setTimeoutCount: globalTimerIds.size,
            setIntervalCount: globalIntervalIds.size,
            totalTimers: globalTimerIds.size + globalIntervalIds.size,
            cleanupHistory: this.cleanupHistory,
            lastCleanupTime: this.lastCleanupTime
        };
    }

    /**
     * 重置清理器
     */
    reset() {
        this.forceCleanupAllTimers();
        this.cleanupHistory = [];
        this.lastCleanupTime = 0;
        console.log('[EmergencyCleaner] 重置完成');
    }
}

// 创建单例实例
const emergencyCleaner = new EmergencyCleaner();

// 定期检查
setInterval(() => {
    emergencyCleaner.checkAndCleanup();
}, 5000); // 每5秒检查一次

export default emergencyCleaner;
